package com.hw01.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hw01.controller.vo.ResultVO;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @ClassName AuthFilter
 * @Description 登录验证过滤器
 * @Author Kx
 * @Date 2025/5/14 10:55
 * @Version 1.0
 */
// 拦截所有请求
//@WebFilter(urlPatterns = "/*")
public class AuthFilter implements Filter {
    // 需要放行的路径都存储在这个集合中
    private static List<String> list;

    /**
     * @author: kx
     * @date: 2025/5/14 11:00
     * @param filterConfig : 过滤器配置
     * @description: 设置需要放行的路径
    */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 定义需要放行的路径
        list = Arrays.asList("/login", "/login.html");
    }

    /**
     * @param servletRequest  : 请求信息
     * @param servletResponse : 响应信息
     * @param filterChain     : 过滤器链
     * @author: kx
     * @date: 2025/5/14 11:00
     * @description: 过滤器逻辑
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 强制转换成Http相关的子类,以便使用HTTP特有的功能
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 放行OPTIONS请求
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            filterChain.doFilter(request, response);
            return;
        }

        // 判断当前请求是否需要放行
        if (list.contains(request.getRequestURI())) {
            // 放行
            filterChain.doFilter(request, response);
        } else {
            // 获取令牌
            String token = request.getHeader("auth");
            // 判断令牌是否为空
            if (token != null) {
                // 放行
                filterChain.doFilter(request, response);
            } else {
                // 获取请求头
                String header = request.getHeader("X-Requested-With");
                // 判断是否是ajax请求
                if ("XMLHttpRequest".equals(header)) {
                    // 创建响应对象
                    ResultVO<String> resultVO = new ResultVO<>();
                    // 设置错误码
                    resultVO.setCode(HttpStatus.UNAUTHORIZED.value());
                    // 设置错误信息
                    resultVO.setMessage("尚未登录");
                    // 设置响应数据格式(告诉客户端响应内容是 JSON 格式)
                    response.setContentType("application/json");
                    // 把响应对象序列化成 JSON 字符串
                    String resultJSON = new ObjectMapper().writeValueAsString(resultVO);
                    // 把 JSON 字符串响应给客户端
                    response.getWriter().write(resultJSON);
                }
            }
        }
    }
}
